//
//  SelectScene.cpp
//  HelloCpp
//
//  Created by apple  on 13-6-15.
//
//

#include "SelectScene.h"

#include "SimpleAudioEngine.h"
#include "CC2DFileCache.h"
#include "Misc.h"
#include "GlobalDef.h"
#include "StartScene.h"
#include "LevelScene.h"
#include "AppMacros.h"

using namespace CocosDenshion;

SelectScene* SelectScene::create()
{
    SelectScene* pScene = new SelectScene;
    if (pScene && pScene->init()) {
        pScene->autorelease();
        return pScene;
    }
    return NULL;
}

void SelectScene::onEnter()
{
    CCScene::onEnter();
}

void SelectScene::onExit()
{
    CCScene::onExit();
}

bool SelectScene::init()
{
    bool bRet = CCScene::init();
    
	CC2DNode* pCC2DNode = CC2DFileCache::sharedCC2DFileCache()->addCC2DNode("level-selected.cc2d");
    CCNode* selectLayer = pCC2DNode->createCCNode(this);
    
    CCMenu* pMenu = dynamic_cast<CCMenu*>(Misc::getChildByName(selectLayer, "Menu"));
    if (pMenu) {
        pMenu->setPosition(0, 0);
    }
	int curLevel = CCUserDefault::sharedUserDefault()->getIntegerForKey("Level", 1);
    for (int i=1; i<=30; i++) {
        std::ostringstream ostr;
        ostr << "btn-level" << i;
        CCMenuItem* pItem = dynamic_cast<CCMenuItem*>(Misc::getChildByName(pMenu, ostr.str().c_str()));
        
        if (pItem) {
			if (i > curLevel)
			{
				pItem->setEnabled(false);
			}
			
            pItem->setTag(i);
            pItem->setTarget(this, SEL_MenuHandler(&SelectScene::menuItemClick));
        }
    }
    
    CCMenuItem* pBackBtn = dynamic_cast<CCMenuItem*>(Misc::getChildByName(selectLayer, "btnBack"));
    pBackBtn->setTag(BACK_MENU_ITEM);
    pBackBtn->setTarget(this, SEL_MenuHandler(&SelectScene::menuItemClick));
    selectLayer->setPosition(0, 0);
    return bRet;
}

void SelectScene::menuItemClick(cocos2d::CCObject *sender)
{
    CCNode* pItem = dynamic_cast<CCNode*>(sender);
    if (pItem->getTag() == BACK_MENU_ITEM) {
        StartScene* pScene = StartScene::create();
        CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(1, pScene));
    }
    else
    {
        CCScene* pScene = LevelScene::create(pItem->getTag());
        CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(1, pScene));
    }
}
